package org.oschina.api.openapi.service;

import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.openapi.dao.OpenApiDAO;
import org.oschina.api.openapi.model.OpenApi;
import org.oschina.api.openapi.vo.OpenApiVo;
import org.oschina.bean.Result;
import org.oschina.api.index.service.IndexService;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OpenApiService extends BaseService {

	@Autowired
	private OpenApiDAO openApiDAO;
	@Autowired
	private IndexService indexService;
	
	/**
	 * 返回
	 * @return
	 */
	//@Require(authority=Module.MODULE_11)
	public List<OpenApiVo> findVo()
	{
		return openApiDAO.findVo();
	}
	
	/**
	 * 创建
	 * @param openApi
	 * @return
	 */
	@Require(authorization=Module.MODULE_11)
	public Result create(OpenApi openApi)
	{
		openApi.setId(_getIndex());
		openApi.setCreate_time(DateUtil.now());
		openApiDAO.create(openApi);
		return ResultUtil.getSuccess(openApi);
	}
	
	/**
	 * 更新
	 * @param openApi
	 * @return
	 */
	@Require(authorization=Module.MODULE_11)
	public Result update(OpenApi openApi)
	{
		if(openApiDAO.update(openApi)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(openApi);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@Require(authorization=Module.MODULE_11)
	public Result remove(int id)
	{
		if(openApiDAO.remove(id)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(Message.DELETE_SUCCESS);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_OPEN_API);
	}
}